'use strict';

module.exports = core;

const path = require('path')
const semver = require('semver')
const colors = require('colors')
const rootCheck = require('root-check')
const userHome = require('user-home')
const pathExists = require('path-exists').sync;
const minimist = require('minimist');
const log = require('@cxz-cli-dev/log')
const pkg = require('../package.json')
const constants = require('./const')
const dotenv = require('dotenv')
const { getNpmSemverVersion } = require('@cxz-cli-dev/get-npm-info')



let args = {}

function core() {
    try{
        checkPkgVersion()
        checkNodeVersion()
        checkRoot()
        checkUserHome()
        checkInputArgs()
        checkEnv()
        checkGlobalUpdate()
    }catch(e){
        log.error(e.message)
    }
}

async function checkGlobalUpdate(){
    // 1. 获取当前版本号
    const currentVersion = pkg.version;
    const npmName = pkg.name;
    // 2. 获取npm最新版本号
    const lastVersion = await getNpmSemverVersion(currentVersion, npmName)
    if(lastVersion && semver.gt(lastVersion,currentVersion)){
        log.warn('更新提示：', colors.yellow(`请手动更新${npmName}，当前版本：${currentVersion},最新版本：${lastVersion}
        更新命令： npm install -g ${npmName}`))
    }
    // 3. 提取所有版本号，对比版本号
    // 4. 获取最新版本号 提示更新
}

function checkEnv(){
    const dotenvPath = path.resolve(userHome,'.env');
    let config;
    if(pathExists(dotenvPath)){
        config = dotenv.config({
            path: dotenvPath
        })
    }
    config = createDefaultConfig()
}

function createDefaultConfig (){
    const cliConfig = {
        home:userHome
    }
    if(process.env.CLI_HOME){
        cliConfig['cliHome'] = path.join(userHome,process.env.CLI_HOME)
    }else{
        cliConfig['cliHome'] = path.join(userHome,constants.DEFAULT_CLI_HOME)
    }
    process.env.CLI_HOME_PATH = cliConfig.cliHome
    return cliConfig
}

function checkInputArgs(){
    args = minimist(process.argv.slice(2))
    checkArgs()
}

function checkArgs(){
    if(args.debug){
       process.env.LOG_LEVEL = 'verbose'  
    }else{
       process.env.LOG_LEVEL = 'info'  
    }
    log.level = process.env.LOG_LEVEL
}

function checkUserHome(){
    if(!userHome || !pathExists(userHome)){
        throw new Error(colors.red('当前用户主目录不存在'))
    }
}

function checkRoot(){
    rootCheck()
}

function checkNodeVersion(){
    if(!semver.gte(process.version,constants.LOWEST_NODE_VERDON)){
        throw new Error(colors.red(`cxz-cli 需要安装V${constants.LOWEST_NODE_VERDON}以上版本Node.js`))
    }
}

function checkPkgVersion(){
    // log.success('cli',pkg.version)
}
